package com.hongxun.design.utils.maputil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.utils.OpenClientUtil;
import com.hongxun.design.mytools.MyLog;

import java.io.File;
import java.util.List;

import static com.hongxun.design.MyApp.context;

/**
 * Created by zerdoor_pc on 2016/7/8.
 */
public class NavigationUtil {
    /**
     * 启动百度地图导航(Native)
     */
    public static void startNavi(Activity activity, LatLng START, LatLng END, String NAME, String ENDNAME) {
        // 构建 导航参数
//        NaviParaOption para = new NaviParaOption()
//                .startPoint(START).endPoint(END)
//                .startName(NAME).endName(ENDNAME);
//
////        if (isInstallByread("com.baidu.BaiduMap")){
////            doStartApplicationWithPackageName(context, "com.baidu.BaiduMap");
////            ToastShow.showShort(context,"如长时间未开启导航，请手动打开百度地图");
////        }
//
//        try {
//            BaiduMapNavigation.openBaiduMapNavi(para, context);
//            ToastShow.showShort(context, "如长时间未开启导航，请检查百度地图启动权限是否打开！");
//        } catch (BaiduMapAppNotSupportNaviException e) {
//            e.printStackTrace();
//            showDialog(context);
//        }

        startNative_Baidu(activity, START, END, NAME, ENDNAME);
    }

    public static void startNative_Baidu(Activity activity, LatLng START, LatLng END, String NAME, String ENDNAME) {
        String s = "";
        try {

            s = "intent://map/direction?origin=latlng:"
                    + getStringLatLng(START) + "|name:" + NAME + "&destination=latlng:" + getStringLatLng(END)
                    + "|name:" + ENDNAME + "&mode=driving&src=" + NAME + "|" + ENDNAME + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end";
            Intent intent = Intent.getIntent(s);//
            activity.startActivity(intent);
        } catch (Exception e) {
            MyLog.L("startNative_Baidu=" + e.getMessage());
            NaviParaOption para = new NaviParaOption()
                    .startPoint(START).endPoint(END)
                    .startName(NAME).endName(ENDNAME);
            BaiduMapNavigation.openWebBaiduMapNavi(para, context);
            //   Toast.makeText(context, "调起百度地图APP失败！", Toast.LENGTH_SHORT).show();
        }
        MyLog.L("startNative_Baidu=" + s);
    }

    public static String getStringLatLng(LatLng latLng) {
        return latLng.latitude + "," + latLng.longitude;
    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private static boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    private static void doStartApplicationWithPackageName(Context activity, String packagename) {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = activity.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = activity.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            activity.startActivity(intent);
        }
    }

    /**
     * 启动百度地图导航(Web)
     */
    public static void startWebNavi(Context context, LatLng START, LatLng END, String NAME, String ENDNAME) {

        // 构建 导航参数
        NaviParaOption para = new NaviParaOption()
                .startPoint(START).endPoint(END)
                .startName(NAME).endName(ENDNAME);

        BaiduMapNavigation.openWebBaiduMapNavi(para, context);
    }

    /**
     * 启动百度地图步行导航(Native)
     */
    public static void startWalkingNavi(Context context, LatLng START, LatLng END, String NAME, String ENDNAME) {


        // 构建 导航参数
        NaviParaOption para = new NaviParaOption()
                .startPoint(START).endPoint(END)
                .startName(NAME).endName(ENDNAME);

        try {
            BaiduMapNavigation.openBaiduMapWalkNavi(para, context);
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            showDialog(context);
        }

    }

    /**
     * 启动百度地图骑行导航(Native)
     */
    public static void startBikingNavi(Context context, LatLng START, LatLng END, String NAME, String ENDNAME) {


        // 构建 导航参数
        NaviParaOption para = new NaviParaOption()
                .startPoint(START).endPoint(END)
                .startName(NAME).endName(ENDNAME);

        try {
            BaiduMapNavigation.openBaiduMapBikeNavi(para, context);
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            showDialog(context);
        }

    }


    /**
     * 提示未安装百度地图app或app版本过低
     */
    public static void showDialog(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                OpenClientUtil.getLatestBaiduMapApp(context);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();

    }
}
